<template>
  <div class="common-layout">
    <el-container>
      <el-header style="min-height: 6vh; margin-top: 1vh">
        <div class="header-content common-div-card">
          <el-form :model="headerSearchForm" label-width="auto" :inline="true">
            <el-form-item label="时间范围">
              <div class="date-select">
                <el-date-picker v-model="headerSearchForm.start" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
                <span>-</span>
                <el-date-picker v-model="headerSearchForm.end" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </el-form-item>
            <el-form-item label="产线">
              <el-select v-model="headerSearchForm.prodLine" clearable style="width: 160px">
                <el-option label="酸轧2280" value="tcm2280" />
                <el-option label="连退1630" value="cal1630" />
                <el-option label="连退2150" value="cal2150" />
                <el-option label="镀锌1870" value="cgl1870" />
              </el-select>
            </el-form-item>
            <el-form-item label="出口卷号">
              <el-input v-model="headerSearchForm.extNo" />
            </el-form-item>
            <el-form-item label="缺陷等级">
              <el-select v-model="headerSearchForm.defectClass" clearable style="width: 160px">
                <el-option label="可利用材" value="可利用材" />
                <el-option label="废品" value="废品" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="原因归户">
              <el-select v-model="headerSearchForm.defectattributioncode" clearable style="width: 160px">
                <el-option label="外部原因" value="外部原因" />
                <el-option label="内部原因" value="内部原因" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <div class="table-container common-div-card">
          <el-table
            :data="tableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            v-loading="loading"
            ref="tableRef"
            :row-class-name="rowClassName"
            :show-overflow-tooltip="true"
            element-loading-text="加载中..."
          >
            <el-table-column label="序号" fixed="left" type="index" width="60px" />
            <el-table-column prop="calcoilid" label="出口卷号" show-overflow-tooltip />
            <el-table-column prop="exwt" label="入口重量[kg]" show-overflow-tooltip />
            <el-table-column prop="rcltotalexwt" label="重卷出口重量[kg]" show-overflow-tooltip />
            <el-table-column prop="lostweight" label="重量损失[kg]" show-overflow-tooltip />
            <el-table-column prop="defectclass" label="缺陷等级" show-overflow-tooltip />
            <el-table-column prop="defectattributioncode" label="原因归户" show-overflow-tooltip />
          </el-table>
        </div>
        <div class="pagination common-div-card">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick, defineComponent } from 'vue';
  import { ElMessage, ElMessageBox, ElTable, TabsPaneContext } from 'element-plus';
  import { ActualPerformanceRollDeviationApi as api } from '/@/api/deviationanalysis/ActualPerformanceRollDeviation';
  import { useRoute } from 'vue-router';
  import dayjs from 'dayjs';

  const rowClassName = ({ row }: { row: any }) => {
    let hasWarning = false;
    return hasWarning ? 'warning-row' : '';
  };

  interface SearchForm {
    start: string;
    end: string;
    prodLine: string;
    extNo: string;
    defectClass: string;
    defectattributioncode: string;
  }
  // 表单数据
  const headerSearchForm = reactive<SearchForm>({
    start: '',
    end: '',
    prodLine: '',
    extNo: '',
    defectClass: '',
    defectattributioncode: '',
  });

  // 表格数据
  const tableData = ref<any>([]);
  const tableRef = ref<InstanceType<typeof ElTable>>();
  const loading = ref(false);

  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取表格数据
  const fetchTableData = async () => {
    loading.value = true;
    try {
      const param = {
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
        dbegin: headerSearchForm.start,
        dend: headerSearchForm.end,
        calcoilid: headerSearchForm.extNo,
        defectclass: headerSearchForm.defectClass,
        linename: headerSearchForm.prodLine,
      };

      const res = await api.getQualityDefectList(param);
      tableData.value = res.data.data;
      pagination.total = res.data.count;
      loading.value = false;
    } catch (error) {
      loading.value = false;
      ElMessage.error('获取数据失败');
    }
  };

  // 查询方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 重置方法
  const handleReset = () => {
    (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach((key) => {
      headerSearchForm[key] = '';
    });
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 初始化加载
  const route = useRoute();
  onMounted(() => {
    if (route.query && route.query.linename) {
      try {
        headerSearchForm.prodLine = route.query.linename as string;
        if (route.query.defectclass) {
          headerSearchForm.defectClass = route.query.defectclass as string;
        }
        if (route.query.start && route.query.end) {
          headerSearchForm.start = dayjs(route.query.start as string).format('YYYY-MM-DD HH:mm:ss');
          headerSearchForm.end = dayjs(route.query.end as string).format('YYYY-MM-DD HH:mm:ss');
        }
        fetchTableData();
      } catch (err: any) {
        headerSearchForm.start = dayjs().subtract(6, 'day').format('YYYY-MM-DD 00:00:00');
        headerSearchForm.end = dayjs().format('YYYY-MM-DD 23:59:59');
        fetchTableData();
        console.error('跳转信息获取失败：' + err.message);
      }
    } else {
      headerSearchForm.start = dayjs().subtract(6, 'day').format('YYYY-MM-DD 00:00:00');
      headerSearchForm.end = dayjs().format('YYYY-MM-DD 23:59:59');
      fetchTableData();
    }
  });

  // // 生命周期钩子
  // onMounted(() => {
  //   fetchTableData();
  // });

  onUnmounted(() => {});
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border: 1px solid #dcdfe6;

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .common-layout {
    width: 99vw;
    min-height: 100vh;
    background-color: #fff;
  }

  .header-content {
    display: flex;
    justify-content: flex-start;
    padding: 1rem 1rem 0 1rem;
    // min-height: 8vh;
    // .el-form {
    //   margin-top: 2vh;
    // }
  }

  .date-select {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    gap: 12px;
  }

  .table-container {
    padding: 0.5rem;
    height: 70vh;

    :deep(.el-table) {
      height: 100%;
      max-width: 100%;
    }
  }

  .pagination {
    margin-top: 2vh;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }

  .warning-row {
    background-color: '#ffe6e6';
  }
</style>
